package com.airpi.heavy_tasks;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;

import com.airpi.activities.LoginActivity;
import com.airpi.connectivity.RaspberryPiDiscoverer;

/**
 * Asynchronous task used to handle the Heavy tasks which the Activity is not able to execute.
 * In this case, it is used to send the Login request through a socket (defined in the Connexion object)
 * @param activity : The activity which instanciate the AsyncTask Object
 */

public class AsyncTaskActivity extends AsyncTask<Void, Integer, Boolean>{
	private Activity activity;
	private String toSend;

	public AsyncTaskActivity(Activity activity, String toSend){
		this.activity = activity;
		this.toSend = toSend;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected void onProgressUpdate(Integer... values){
		super.onProgressUpdate(values);
	}

	/**
	 * Method called after onPreExecute(), which allows to execute the Heavy tasks in the background of the Activity
	 */

	@Override
	protected Boolean doInBackground(Void... arg) {
		//Retrieve the last IP found in the preferences
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.activity); 
		String ip = sharedPrefs.getString(RaspberryPiDiscoverer.PREFS_LAST_FOUND, null);

		//Creation of the Connection to the Server
		Connexion co = new Connexion(ip);

		Log.e("toSend ASTA", toSend);

		if(co.getSocket() != null) {
			//Send the Nickname and the Password entered by the User.
			co.sendToServer(this.toSend);

			String answer = co.answerFromServer();
			System.out.println(answer);
			if(answer.length() > 16){
				if (answer.substring(16,21).contains("admin")){
					sharedPrefs.edit().putBoolean(LoginActivity.USER_STATUS, true).commit();
				}
				else sharedPrefs.edit().putBoolean(LoginActivity.USER_STATUS, false).commit();
				
				sharedPrefs.edit().putString(LoginActivity.USER_ID, answer.substring(21)).commit();
				return (answer.contains("ServerOK[Login]"));
			}
			else if(answer.length()<=16){
				return (answer.contains("ServerOK[Logout]"));
			}
			else
				return false;

		}
		else 
			return false;

	}

	/**
	 * @param result : true if the server answered that the request was OK and that the User is connected, else, false
	 * Method handling the launch of the Main Activity
	 */

	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
	}
}